/*
 * NewSPCFrame.java
 *
 * Created on Dec 15, 2011, 11:52:49 PM
 */
package gui;

/**
 *
 * @author suzann
 */

/*
 * Import Java Classes
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.*;

import util.Activity;
import util.ActivityComment;
import util.Authentication;
import util.ErrorMessage;

/*
 * Import own Classes
 */
import db.entity.*;
import db.*;

public class NewSPCFrame extends javax.swing.JFrame {

    /** Creates new form NewSPCFrame */
    public NewSPCFrame() {
        initComponents();
        dm = new DatabaseManager();
        dlModel = new DefaultListModel();
        _instance = this;
        initStations();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlsStation = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jlsMount = new javax.swing.JList();
        jbtStart = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("CTRL + Click to select multiple target");

        jLabel2.setText("Station");

        jScrollPane1.setViewportView(jlsStation);

        jLabel3.setText("Lot ID");

        jlsMount.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Mount 1", "Mount 2", "Both" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jlsMount.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(jlsMount);

        jbtStart.setText("Start");
        jbtStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtStartActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jbtStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jScrollPane2))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE))))))
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtStart)
                .addGap(36, 36, 36))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-329)/2, (screenSize.height-597)/2, 329, 597);
    }// </editor-fold>

    private void jbtStartActionPerformed(java.awt.event.ActionEvent evt) {
        startSPC();
    }
    
    /****************************************************************************
     * INTERNAL OPERATIONS : THE FRAME
     ****************************************************************************/
    /**
     * Initialize lists in the Station
     */
    private void initStations()
    {
    	dlModel.clear();
    	
        //get the list of Stations from DB
        List <TaperMap> taperMaps = dm.listTaperMap();
        List <String> stations = new ArrayList<String>();
       
        //set the JList of station with the default model
        jlsStation.setModel(dlModel);
        
        for(int i  = 0; i < taperMaps.size(); i++)
        {
            if(taperMaps.get(i).getLeftTaper()!= null)
                stations.add(i, taperMaps.get(i).getLeftTaper());
            //    stations.add(i, taperMaps.get(i).getStationName() + " " + taperMaps.get(i).getLeftTaper());
            if(taperMaps.get(i).getRightTaper()!= null)
                stations.add(i, taperMaps.get(i).getRightTaper());
            //    stations.add(i, taperMaps.get(i).getStationName() + " " + taperMaps.get(i).getRightTaper());
        }
        
        //sort the stations according to station number before displaying them out
        Collections.sort(stations);
        
        for(int i  = 0; i < stations.size(); i++)
        {            
            dlModel.add(i, stations.get(i));
        }
    }
    
    private void startSPC()
    {
    	// When user trying to Start SPC, authenticate the user first.
        // If Authenticated, save the value, else prompt to enter the user again
        String username = null;
        boolean isEdit = false;
        do
        {
            username = Authentication.authenticateUser();
            if(username.equals("Invalid"))
            {
                JOptionPane.showMessageDialog(this, "Your username is invalid.\nPlease enter your username again.", "Authentication Failure", JOptionPane.WARNING_MESSAGE);
                System.out.println("Authentication failure attempted."); //Can be included into activity log later.
                continue;
            }
            else if (username.equals("Exit"))
            {
                System.out.println("Edit pressure values action terminated."); //Can be included into activity log later.
                return;
            }
            else
            {
                if (username != null)
                {                    
                    isEdit = true;
                }
            }
        }while(isEdit == false);

	   	// Get Activity Comment
	   	String comment = ActivityComment.getComment();
	   	if(comment.equals("Exit"))
	   		return ;
   	
        // User authenticated. Validate User Input and update database.
        String errorMsg = "";
        if(jlsStation.getSelectedIndices().length == 0)
        	errorMsg += "Please select a Station. \n";
        
        if(jTextField1.getText().equals(""))
        	errorMsg += "Please fill in Lot ID. \n";
        
        if(jlsMount.getSelectedIndices().length == 0)
        	errorMsg += "Please select a Mount. \n";
        
        if(errorMsg.equals(""))
        {
        	String dcElement, lotID, mountID;
        	int mountID_int;
        	
        	lotID = jTextField1.getText();
        	mountID = jlsMount.getSelectedValue().toString();
        	if(mountID.equals("Mount 1"))
        		mountID_int = 1;
        	else if (mountID.equals("Mount 2"))
        		mountID_int = 2;
        	else
        		mountID_int = 3;
        	
        	ArrayList<TaperSpc> taperList = new ArrayList<TaperSpc>();
        	for(Object value : jlsStation.getSelectedValues())
        	{
        		dcElement = value.toString();
        		
        		TaperSpcPK spcItem_PK = new TaperSpcPK();
        		spcItem_PK.setDcElement(dcElement);
        		spcItem_PK.setLotID(lotID);
        		
        		TaperSpc spcItem = new TaperSpc();
        		spcItem.setId(spcItem_PK);
        		spcItem.setMountID(mountID_int);
        		spcItem.setSpcStartDate(new Date());
        		
        		taperList.add(spcItem);
        	}
        	
        	DatabaseManager db = new DatabaseManager();
        	db.updateTaperSpc((List)taperList);
        	
        	for(Object value : jlsStation.getSelectedValues())
        	{
        		Activity.log("Started SPC for "+value.toString(), username, comment);
        	}
        	JOptionPane.showMessageDialog(null, "All SPC successfully started.", "SPC Started", JOptionPane.PLAIN_MESSAGE);
        }
        else
        	ErrorMessage.displayError(ErrorMessage.WARNING_ERROR, false, "Validation Error", errorMsg);
    }
    
    public static void updateTaperList()
    {
    	_instance.initStations();
    }

    
    public void addNotify() {
        super.addNotify();
        // Buffer
        createBufferStrategy(2);           
        //BufferStrategy strategy = getBufferStrategy();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewSPCFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewSPCFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewSPCFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewSPCFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewSPCFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton jbtStart;
    private javax.swing.JList jlsMount;
    private javax.swing.JList jlsStation;
    // End of variables declaration
    
    //User defined variables
    private db.DatabaseManager dm;
    private DefaultListModel dlModel;
    private static NewSPCFrame _instance;
    
}
